<template>
  <div style="width: 100%; height: 80vh">
    <!-- 查询接口似乎没做 -->
    <!-- <Search :search="search" :reset="reset">
      <template v-slot:body>
        <el-form-item label="箱号" prop="barcode">
          <el-input v-model="query.barcode" name="barcode" clearable />
        </el-form-item>
      </template>
    </Search> -->

    <div class="table-default-barcode" style="height: 70vh">
      <el-button type="primary" @click="closedialog">关闭</el-button>
      <el-button type="success" @click="print">打印</el-button>
      <el-button type="success" @click="printAll">全部打印</el-button>
      <!-- <el-button type="warning" @click="outputHandler" v-loading.fullscreen.lock="fullscreenLoading">导出</el-button> -->
      <el-button type="warning" @click="PDFHandler" v-loading.fullscreen.lock="fullscreenLoading">导出</el-button>
      <el-button type="warning" @click="PDFAllHandler" v-loading.fullscreen.lock="fullscreenLoading">全部导出</el-button>
      <el-button type="danger" @click="deleteHandler(1)" v-loading.fullscreen.lock="fullscreenLoading" v-if="props.curtemporary == '未暂收'">批量作废</el-button>
      <el-button type="primary" @click="deleteHandler(0)" v-loading.fullscreen.lock="fullscreenLoading" v-if="props.curtemporary == '未暂收'">批量反作废</el-button>
      <el-button type="success" @click="saveHandler" v-loading.fullscreen.lock="fullscreenLoading" v-if="props.curtemporary == '未暂收'">保存</el-button>
      <!-- <div style="height: 90%;border: 1px solid #000; overflow: auto;"> -->
      <el-form :model="tableForm" label-width="100px" ref="ruleFormRef">
        <el-table :data="tableForm.tableData" class="mt-3" border @selection-change="handleSelectionChange" style="height: 67vh; border: 1px solid #ccc; overflow: auto">
          <el-table-column type="selection" width="55" size="lange" />
          <el-table-column prop="barcode" label="箱号" min-width="150" />
          <el-table-column prop="supplierOrder" label="供应商单号" min-width="170" />
          <el-table-column prop="fmaterialid" label="物料代码" min-width="100" />
          <el-table-column prop="fmaterialname" label="物料名称" min-width="250" />
          <el-table-column prop="fsupplierid_number" label="物料代号" min-width="150" />
          <el-table-column
            prop="void"
            label="作废状态"
            min-width="120"
            v-if="props.curtemporary == '未暂收'"
            :filters="[
              { text: '作废', value: 1 },
              { text: '未作废', value: 0 },
            ]"
            :filter-method="filterTag"
          >
            <template #default="scope">
              <el-form-item :prop="'tableForm.tableData' + scope.$index + '.void'">
                <el-switch
                  v-model="scope.row.void"
                  inline-prompt
                  :active-value="activeValue"
                  :inactive-value="inactiveValue"
                  active-text="未作废"
                  inactive-text="已作废"
                  style="--el-switch-on-color: #13ce66"
                />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div style="display: flex; justify-content: center; width: 100%; margin-top: 10px">
        <el-pagination
          v-model:current-page="pages.current"
          v-model:page-size="pages.limit"
          layout="total, prev, pager, next, jumper"
          :total="pages.total"
          @current-change="handleCurrentChange"
          background
        />
      </div>
      <!-- </div> -->
    </div>

    <el-dialog v-model="printShow" title="预览" width="60%">
      <barCode :barcodeList="barcodeList" :PrintNow="PrintNow" :output="output" @send-data="getDataHandler"></barCode>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="warning" @click="PrintNow = true">确认打印</el-button>
          <el-button @click="closeHandler">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog v-model="PDFShow" title="预览" width="60%">
      <!-- // storage.setItem('barcodeArr', barcodeList.value) -->
      
      <barCodePDF :barcodeArr="barcodeList" @send-close="getCloseSend"></barCodePDF>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, reactive } from 'vue'
import Create from './create.vue'
import { useGetList } from '/admin/composables/curd/useGetList'
import { useDestroy } from '/admin/composables/curd/useDestroy'
import { useOpen } from '/admin/composables/curd/useOpen'
import http from '/admin/support/http'
import { ElMessage } from 'element-plus'
import storage from '/admin/utils/storage'
import barCode from './barCode.vue'
import barCodePDF from './barCodePDF.vue'
import { useRouter, useRoute } from 'vue-router'

import FileSaver from 'file-saver'
const exportPdf = (url, name) => {
  let oReq = new XMLHttpRequest()
  let URLToPDF = url
  oReq.open('GET', URLToPDF, true)
  oReq.responseType = 'blob'
  oReq.onload = function () {
    let file = new Blob([oReq.response], {
      type: 'application/pdf',
    })
    FileSaver.saveAs(file, name)
  }
  oReq.send()
}
// import lang from 'element-plus/lib/locale/lang/zh-cn';

const router = useRouter()
const route = useRoute()
const props = defineProps({
  supplierId: String,
  curtemporary: String,
})

const api = `purchasing/barcodeApi/${props.supplierId}`

// const { data, query, search, reset, loading } = useGetList(api)
// const { destroy, deleted } = useDestroy()
// const { open, close, title, visible, id } = useOpen()

// const tableForm.tableData = computed(() => data.value?.data)

let pages = reactive({
  totla: null,
  current: 1,
  limit: 1000,
})
let tableForm = reactive({
  tableData: [],
})
let activeValue = ref(0)
let inactiveValue = ref(1)

const fullscreenLoading = ref(false)

const filterTag = (value: string, row) => {
  console.log(value, row)
  return row.void == value
}

const getprintBarcode = () => {
  fullscreenLoading.value = true
  let data = {
    limit: pages.limit,
    page: pages.current,
  }
  http.get(`purchasing/barcodeApi/${props.supplierId}`, data).then(r => {
    console.log('打印箱号的请求数据', r.data.data)
    tableForm.tableData = r.data.data
    pages.total = r.data.total
    fullscreenLoading.value = false
  })
}
getprintBarcode()

console.log('箱号列表：', tableForm.tableData)
const barArr = ref([])
const printShow = ref(false)
const PDFShow = ref(false)
const PrintNow = ref(false)
const output = ref(false)

// const handleSizeChange = (val) => {
//   console.log(`${val} items per page`)
// }
const handleCurrentChange = val => {
  pages.current = val
  getprintBarcode()
  // console.log(`current page: ${val}`)
}

let emit = defineEmits(['send-data'])

// 关闭当前弹窗
const closedialog = () => {
  emit('send-close', false)
}

const arrId = ref([])

const handleSelectionChange = (val: any) => {
  const arr = []
  for (const obj of val) {
    arr.push(obj.barcode)
  }
  const uniqueSet = new Set(arr)
  barArr.value = [...uniqueSet]
  // console.log('选中后的img', barArr.value)

  // 收集选中数组id
  arrId.value = val.map(ele => {
    return {
      id: ele.id,
      void: ele.void,
    }
  })
  // console.log('收集选中数组id', arrId.value)
}

const print = () => {
  // console.log('打印', barArr.value)
  if (barArr.value.length != 0) {
    printShow.value = true
    getPrint(barArr.value)
  } else {
    ElMessage.warning('请选择箱号！')
  }
}
const barcodeList = ref([])

const printAll = () => {
  handleSelectionChange(tableForm.tableData)
  getPrint(barArr.value)
}

// 选择导出
const PDFHandler = () => {
  if (barArr.value.length != 0) {
    console.log('导出选中的barArr', barArr.value)
    const data = {
      barcode: barArr.value,
    }
    console.log('请求打印发送数据：', data)
    fullscreenLoading.value = true
    http
      .post('/purchasing/codePdf', data)
      .then(r => {
        fullscreenLoading.value = false
        let res = r.data.data
        console.log('请求PDF的接口', res)
        // window.location.href = res.pdfUrl
        const w = window.open('about:blank')
        w.location.href = res.pdfUrl
        // exportPdf(res.pdfUrl,'测试导出')
      })
      .catch(error => {
        fullscreenLoading.value = false
      })
  } else {
    ElMessage.warning('请选择箱号！')
  }
}

// 全部导出
const PDFAllHandler = () => {
  fullscreenLoading.value = true
  http
    .post(`/purchasing/codePdfall/${props.supplierId}`)
    .then(async r => {
      fullscreenLoading.value = false
      let res = r.data.data
      const w = window.open('about:blank')
      w.location.href = res.pdfUrl
    })
    .catch(error => {
      fullscreenLoading.value = false
    })
}

const outputHandler = () => {
  // handleSelectionChange(tableForm.tableData)
  if (barArr.value.length != 0) {
    console.log('导出选中的barArr', barArr.value)

    const data = {
      barcode: barArr.value,
    }
    console.log('请求打印发送数据：', data)
    fullscreenLoading.value = true
    http.post('/purchasing/barcodePrinting', data).then(r => {
      let res = r.data.data
      console.log('返回的打印', res)
      if ((res.code = '10000')) ElMessage.success('跳转导出')
      barcodeList.value = res
      console.log('返回的打印数据：', barcodeList.value)
      // printShow.value = true
      // storage.setItem('barcodeArr', barcodeList.value)

      PDFShow.value = true
      // router.push(`/purchasing/barCodePDF`)
      fullscreenLoading.value = false
    })
  } else {
    ElMessage.warning('请选择箱号！')
  }
}

const getPrint = arr => {
  const data = {
    barcode: arr,
  }
  // console.log('请求打印发送数据：', data)
  http.post('/purchasing/barcodePrinting', data).then(r => {
    let res = r.data.data
    // console.log('返回的打印', res)
    if ((res.code = '10000')) ElMessage.success('确认勾选，跳转打印')
    barcodeList.value = res
    console.log('返回的打印数据：', barcodeList.value)
    printShow.value = true
  })
}

// // 全选触发
// let handlerSelectAll = options => {
//   console.log(options)
//   let flag = options.every(item => item.fsupplierid_number == options[0].fsupplierid_number)
//   if (!flag) {
//     ElMessage.warning('只能勾选同一供应商哦~')
//   }
//   tableData.value.forEach(item => {
//     console.log(item.fsupplierid_number, options[0].fsupplierid_number)
//     if (item.fsupplierid_number !== options[0].fsupplierid_number) {
//       multipleTableRef.value.toggleRowSelection(item, false)
//     }
//   })
// }

// 保存
const saveHandler = () => {
  console.log(tableForm.tableData)
  let sendData = tableForm.tableData.map(ele => {
    return {
      id: ele.id,
      void: ele.void,
    }
  })

  fullscreenLoading.value = true
  http
    .post('/purchasing/barcodevoid', sendData)
    .then(r => {
      let res = r.data.data
      // console.log('删除请求返回', res)
      ElMessage.success('保存成功')
      fullscreenLoading.value = false
      getprintBarcode()
    })
    .catch(error => {
      fullscreenLoading.value = false
    })
}

// 作废
const deleteHandler = flag => {
  let sendData = null
  // if (item == 'all') {
  if (arrId.value.length == 0) {
    ElMessage.warning('请先选择箱号')
  } else {
    console.log('没有参数，批量')
    sendData = arrId.value.map(ele => {
      return {
        id: ele.id,
        void: flag,
      }
    })
    console.log('删除id数据', sendData)
    fullscreenLoading.value = true
    http
      .post('/purchasing/barcodevoid', sendData)
      .then(r => {
        let res = r.data.data
        // console.log('删除请求返回', res)
        ElMessage.success('修改成功')
        fullscreenLoading.value = false
        getprintBarcode()
      })
      .catch(error => {
        fullscreenLoading.value = false
      })
  }
}

const closeHandler = () => {
  // barArr.value = []
  printShow.value = false
}
const getCloseSend = value => {
  PDFShow.value = value
}

const getDataHandler = () => {
  console.log('接收到子组件传值')
  PrintNow.value = false
}

onMounted(() => {
  getprintBarcode()
  // search()
  // deleted(reset)
  // 设置 ElementUI 的国际化语言为中文
  //  locale(lang);
  // 设置日期控件的国际化语言为中文（如果需要）
  // dayjs.locale("zh-cn");
})
</script>


<style lang="css" scoped>
.spanClass {
  margin-left: 10px;
}

.btn {
  margin: 20px 10px;
}

</style>